//
//  AppDelegate.m
//  PlayBall
//
//  Created by Edward Zhang on 12-5-4.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AppDelegate.h"
#import <QuartzCore/QuartzCore.h>
//#import "DataVerifier.h"
#import "Reachability.h"
//#import "AlixPay.h"
//#import "AlixPayResult.h"
#import <sys/utsname.h>
#import "JddGlobal.h"
#import "JddLotteryHallViewController.h"
#import "AppGuideViewController.h"
#import "MobClick.h"

@interface AppDelegate (){
    AppGuideViewController *_guideVC;
}



- (BOOL)isSingleTask;
- (void)parseURL:(NSURL *)url application:(UIApplication *)application;

@end

@implementation AppDelegate

@synthesize window = _window;
@synthesize navigationController = _navigationController;
@synthesize networktype;
@synthesize remoteHostStatus;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //注册通知
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                                           UIRemoteNotificationTypeAlert |
                                                                           UIRemoteNotificationTypeSound)];
    
    networktype = 1;
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    //初始化
    [JddGlobal sharedInstance].window = self.window;
    
    JddLotteryHallViewController *lotteryHall = [JddLotteryHallViewController sharedInstance];
    self.navigationController = [[JddNavigationController alloc] initWithRootViewController:lotteryHall];

    //[MobClick startWithAppkey:@"56988e7de0f55a862a0014ed" reportPolicy:BATCH   channelId:nil];
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    //[MobClick setAppVersion:version];
    
    
    // 监测网络情况
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
	hostReach = [Reachability reachabilityWithHostName: @"www.baidu.com"];
	[hostReach startNotifier];
    
    //1.判断是否登录
    //JddLoginViewController *loginctrl = [[JddLoginViewController alloc]init];
    
   
    
    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];
    
    
    
    
    //modify by rainy  remove guideImg
//    [self addGuideImgView];
    /*
	 *单任务handleURL处理
	 */
	if ([self isSingleTask]) {
		NSURL *url = [launchOptions objectForKey:@"UIApplicationLaunchOptionsURLKey"];
		
		if (nil != url) {
			[self parseURL:url application:application];
		}
	}
    return YES;
}

- (BOOL)isSingleTask{
	struct utsname name;
	uname(&name);
	float version = [[UIDevice currentDevice].systemVersion floatValue];//判定系统版本。
	if (version < 4.0 || strstr(name.machine, "iPod1,1") != 0 || strstr(name.machine, "iPod2,1") != 0) {
		return YES;
	}
	else {
		return NO;
	}
}

- (void) reachabilityChanged: (NSNotification* )note
{
	Reachability* curReach = [note object];
	NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    
    NSInteger nownet = [JddCommonFunction checkNetWork]?1:0;
    if (nownet == 0&&nownet!=networktype) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                        message:@"网络连接不可用，请检查网络设置"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
        networktype = 0;
        if (![alert isVisible]) {
            [alert show];
        }else {
            [alert setMessage:@"网络连接不可用，请检查网络设置"];
        }
        
    }else {
        if (nownet==1) {
            networktype = 1;
        }
    }
    
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
	[self parseURL:url application:application];
	return YES;
}

-(BOOL) application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //JiangDuoDuo-IOS://orders?backType=5 //&issueId=390853&UserId=jswjwby&resultCode=0 
    NSString *urlPath = [url host];
    if([urlPath isEqualToString:@"orders"])
    {
        NSDictionary *urlDic = [JddCommonFunction dictionaryFromQuery:[url query] usingEncoding:NSUTF8StringEncoding];
        NSString *backType = [urlDic objectForKey:@"backType"];
        if([backType isEqualToString:@"0"]) //购彩纪录
        {
            [self.navigationController popToRootViewControllerAnimated:NO];
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_BUY_HISTORY
                                                                    fromController:self.navigationController
                                                                        withObject:nil
                                                                       withObject2:nil];
        }
        else if([backType isEqualToString:@"1"]) //合买大厅
        {
            /*
            [self.navigationController popToRootViewControllerAnimated:NO];
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_TOGETHER_BUY
                                                                    fromController:self.navigationController
                                                                        withObject:nil
                                                                       withObject2:nil];
             */
             JddTogetherBuyViewController *togetherBuy = [JddTogetherBuyViewController sharedInstance];
            [togetherBuy titleAction:nil];
        }
        else if([backType isEqualToString:@"8"]) //充值
        {
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_SELECT_RECHARGE_WAY
                                                                    fromController:self.navigationController
                                                                        withObject:nil
                                                                       withObject2:nil];
        }
        else //购彩大厅
        {
            //[self.navigationController popToRootViewControllerAnimated:NO];
            /*
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_LOTTERY_HALL
                                                                    fromController:self.navigationController
                                                                        withObject:nil
                                                                       withObject2:nil];
             */
        }
    }
    else
    {
        //支付宝APP http://itunes.apple.com/cn/app/id535715926?mt=8
        [self parseURL:url application:application];
    }
    
    
    return YES;
}

- (void)parseURL:(NSURL *)url application:(UIApplication *)application {
//	AlixPay *alixpay = [AlixPay shared];
//	AlixPayResult *result = [alixpay handleOpenURL:url];
//	if (result) {
//		//是否支付成功
//        if (9000 == result.statusCode) {
//            NSRange range=  [result.userid rangeOfString:@"userid=\""];
//            //快捷登录
//            if((range.location>0)&&(range.length>0))
//                {
//                NSString* temp = [result.userid substringFromIndex:(range.location+8)];
//                NSRange temprange = [temp rangeOfString:@"\""];
//                NSString* userid = [temp substringToIndex:temprange.location];
//                range = [result.userid rangeOfString:@"token=\""];
//                if (range.length > 0)
//                    {
//                    [UIColor grayColor];
////                    temp = [result.userid substringFromIndex:0];
////                    temprange = [[result.userid substringFromIndex:8] rangeOfString:@"\""];
////                    NSString *token = [temp substringToIndex:temprange.location];
//                    //
//                    [[NSNotificationCenter defaultCenter]postNotificationName:ALIPAY_ID_MESSAGE object:userid];
//                    }
//                }
//            //支付
//            else{
//                id<DataVerifier> verifier = CreateRSADataVerifier([[NSBundle mainBundle] objectForInfoDictionaryKey:@"RSA public key"]);
//                if ([verifier verifyString:result.resultString withSign:result.signString]) {
//                    [JddCommonFunction messageBoxWithMessage:@"充值成功"];
//                    [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_USER_CENTER
//                                                                         fromController:self.navigationController
//                                                                             withObject:nil
//                                                                            withObject2:nil];
//                }
//                else {
//                    [JddCommonFunction messageBoxWithMessage:@"签名失效"];
//                }
//            }
//        }
//        else {
//            [JddCommonFunction messageBoxWithMessage:result.statusMessage];
//            
//        }
//	}
}


- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
//    [[JddGlobalParameter sharedInstance] load];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [self.inputView reloadInputViews];
//    [[JddGlobalParameter sharedInstance] load];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [[NSNotificationCenter defaultCenter]postNotificationName:
     CQSS_MESSAGE object:nil];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [[JddGlobalParameter sharedInstance] save];
}


- (void)addGuideImgView
{
    NSNumber* object = [[NSUserDefaults standardUserDefaults] objectForKey:K_UserDefault_IsShowAppGuideImage];
    if (object == nil || [object boolValue] == YES) {
        if (_guideVC == nil) {
            _guideVC = [[AppGuideViewController alloc] init];
        }
        [_guideVC startGuide];
        
    }
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"deviceToken:{%@}",deviceToken);
    NSString *tokeStr = [NSString stringWithFormat:@"%@",deviceToken];
    if ([tokeStr length] == 0) {
        return;
    }
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"{<>}"];
    tokeStr = [tokeStr stringByTrimmingCharactersInSet:set];
    tokeStr = [tokeStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (tokeStr.length == 0) {
        return;
    }
    [[NSUserDefaults standardUserDefaults] setObject:tokeStr forKey:K_UserDefault_DeviceToken];
}

//如果远程推送消息来了,用户点击了推送消息,或者应用已经处于打开状态,系统都会自动调用以下委托
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSLog(@"远程通知");
    //NSLog(@"%@",userInfo);
    //
    //NSDictionary *cpn = [userInfo objectForKey:@"cpn"];
    //[self pushPayResult:cpn];
    
}

@end

